package fr.enseirb.webxml.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;

import fr.enseirb.webxml.util.ServletToolkit;
import fr.enseirb.webxml.util.XMLToolkit;
import fr.enseirb.webxml.data.xml.XMLMediator;

/**
 * Servlet implementation class AboutServlet
 */
public class ListTasksServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListTasksServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sResponse = "";

		String uri = request.getRequestURI();
		Properties params = ServletToolkit.parseURLParams(request);

		if (uri.contains("task/list/xml")) {
			if (params.containsKey("id")) {
				int id = Integer.parseInt(params.getProperty("id"));
				sResponse = XMLMediator.getTask(id);
			} else {
				sResponse = XMLMediator.getTasks();
			}
			response.setHeader("Content-Type", "application/xml");
		} else if (uri.contains("task/list")) {
			String xml = XMLMediator.getTasks();

			String user = "";
			if (params.containsKey("ownerNameFilter")) {
				user = params.getProperty("ownerNameFilter");
			}
			Map<String, String> xslParams = new HashMap<String, String>();
			xslParams.put("user", user);

			sResponse = XMLToolkit.transformXML(
				xml, "resources/xsl/common/task_list.xsl", xslParams
			);
		}

		ServletToolkit.writeResponse(response, sResponse);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)ñ
	 * @Override
	 */
	// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// 	teacherName = ServletToolkit.getPostData(req);
	// 	ServletToolkit.writeResponse(resp, "OK");
	// }
}
